﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using BUS;
using VO;
namespace ManagementBooks
{
    public partial class XuatSach : Form
    {
        string TenDN;
        KhachHang_BUS _KhachHangBUS = new KhachHang_BUS();
        SachBUS _SachBUS = new SachBUS();
        HoaDon_BUS _HoaDonBUS = new HoaDon_BUS();
        public XuatSach()
        {
            InitializeComponent();
            Sender = new SendMessage(GetMessage);
        }
        public delegate void SendMessage(string TenDangNhap);
        public SendMessage Sender;
        private void GetMessage(string TenDangNhap)
        {
            this.TenDN = TenDangNhap;
        }
        private void XuatSach_Load(object sender, EventArgs e)
        {
            loadcbbkh();
            loaddanhmucsach();
        }

        private void bntThoat_Click(object sender, EventArgs e)
        {
            if (DialogResult.Yes == MessageBox.Show("Bạn có chắc muốn thoát hay không?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
            {
                Application.Exit();
            }
        }
        private void loadcbbkh()
        {
            cbbKhachHang.DataSource = _KhachHangBUS.allKhachHang();
            cbbKhachHang.DisplayMember = "HoTen";
            cbbKhachHang.ValueMember = "MaKhachHang";
            this.cbbKhachHang.AutoCompleteMode = AutoCompleteMode.Suggest;
            this.cbbKhachHang.AutoCompleteSource = AutoCompleteSource.ListItems;
        }
        private void loaddanhmucsach()
        {
            grvDanhMucSach.DataSource = _SachBUS.showDanhMucSach();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            loaddanhmucsach();
        }
        string Tongtienall;
        private void TinhTongTienall()
        {
            float sum = 0;
            for (int i = 0; i < GrvDanhSachKH.Rows.Count; i++)
            {
                sum += Convert.ToInt64(GrvDanhSachKH["TongTien1", i].Value.ToString());
            }
            Tongtienall = String.Format("{0:0,0}", sum);
        }
        private void btnThem_Click(object sender, EventArgs e)
        {
            if(cbbNhap.SelectedIndex==0)
            {
                int rowIndex = CheckExitName(txtMaSach.Text);
                if (rowIndex != -1)
                {
                    if (MessageBox.Show("Mặt hàng đã tồn tại,Bạn có muốn thêm số lượng?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                        return;
                }
                if (rowIndex == -1)
                {
                    if (txtSoLuong.TextLength == 0)
                    {
                        MessageBox.Show("Xin hãy thêm số lượng cho sản phẩm!");
                    }
                    else
                    {
                        cbbKhachHang.Enabled = false;
                        if (txtTenKH.Text == "" || txtDiaChi.Text == "" || txtDT.Text == "" || txtSoLuong.Text == "")
                        {
                            MessageBox.Show("Bạn chưa nhập đủ thông tin");
                        }
                        else
                        {
                            tinhtongtien();
                            DataGridViewRow row = new DataGridViewRow();
                            row.CreateCells(GrvDanhSachKH);
                            row.Cells[0].Value = GrvDanhSachKH.Rows.Count + 1;
                            row.Cells[1].Value = masach;
                            row.Cells[2].Value = txtTenKH.Text;
                            row.Cells[3].Value = txtGhiChu.Text;
                            row.Cells[4].Value = optNam.Checked ? "Nam" : "Nữ";
                            row.Cells[5].Value = txtDiaChi.Text;
                            row.Cells[6].Value = txtDT.Text;
                            row.Cells[7].Value = TenSachHD;
                            row.Cells[8].Value = txtSoLuong.Text;
                            row.Cells[9].Value = dongia;
                            row.Cells[10].Value = tongtien;
                            GrvDanhSachKH.Rows.Add(row);
                            if (GrvDanhSachKH.Rows.Count > 0)
                            {
                                txtTenKH.Enabled = false;
                                txtDiaChi.Enabled = false;
                                txtDT.Enabled = false;
                                txtGhiChu.Enabled = false;
                            }
                            TinhTongTienall();
                        }         
                    }
                }
                else
                {
                    DataGridViewRow row = GrvDanhSachKH.Rows[rowIndex];
                    float soLuongcu = float.Parse(row.Cells["SoLuong"].Value.ToString());
                    float soLuong = 0;
                    float.TryParse(txtSoLuong.Text, out soLuong);
                    row.Cells["SoLuong"].Value = soLuong + soLuongcu;
                    float giaBan = 0;
                    float.TryParse(dongia, out giaBan);
                    row.Cells["TongTien"].Value = (soLuongcu + soLuong) * giaBan;
                    TinhTongTienall();
                }         
            }
           else if(cbbNhap.SelectedIndex==1)
            {
                int rowIndex = CheckExitName(txtMaSach.Text);
                if (rowIndex != -1)
                {
                    if (MessageBox.Show("Mặt hàng đã tồn tại,Bạn có muốn thêm số lượng?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                        return;
                }
                if (rowIndex == -1)
                {
                    if (txtSoLuong.TextLength == 0)
                    {
                        MessageBox.Show("Xin hãy thêm số lượng cho sản phẩm!");
                    }
                    else
                    {
                        cbbKhachHang.Enabled = true;
                        txtTenKH.Enabled = false;
                        txtDiaChi.Enabled = false;
                        txtDT.Enabled = false;
                        txtGhiChu.Enabled = false;
                        DataTable dt = new DataTable();
                        dt = _SachBUS.ThongTinKhachHang(Convert.ToInt32(cbbKhachHang.SelectedValue.ToString()));
                        tinhtongtien();
                        DataGridViewRow row = new DataGridViewRow();
                        row.CreateCells(GrvDanhSachKH);
                        row.Cells[0].Value = GrvDanhSachKH.Rows.Count + 1;
                        row.Cells[1].Value = masach;
                        row.Cells[2].Value = dt.Rows[0]["HoTen"].ToString();
                        row.Cells[3].Value = dt.Rows[0]["GhiChu"].ToString();
                        row.Cells[4].Value = dt.Rows[0]["GioiTinh"].ToString() == "1" ? "Nam" : "Nữ";
                        row.Cells[5].Value = dt.Rows[0]["DiaChi"].ToString();
                        row.Cells[6].Value = dt.Rows[0]["DienThoai"].ToString();
                        row.Cells[7].Value = TenSachHD;
                        row.Cells[8].Value = txtSoLuong.Text;
                        row.Cells[9].Value = dongia;
                        row.Cells[10].Value = tongtien;
                        GrvDanhSachKH.Rows.Add(row);
                        if (GrvDanhSachKH.Rows.Count > 0)
                        {
                            cbbKhachHang.Enabled = false;
                        }
                    }
                }
                else
                {
                    DataGridViewRow row = GrvDanhSachKH.Rows[rowIndex];
                    float soLuongcu = float.Parse(row.Cells["SoLuong"].Value.ToString());
                    float soLuong = 0;
                    float.TryParse(txtSoLuong.Text, out soLuong);
                    row.Cells["SoLuong"].Value = soLuong + soLuongcu;
                    float giaBan = 0;
                    float.TryParse(dongia, out giaBan);
                    row.Cells["TongTien1"].Value = (soLuongcu + soLuong) * giaBan;
                    TinhTongTienall();
                }         
            }
        }

        private void grvDanhMucSach_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
        {
            int dem = e.RowIndex;
            grvDanhMucSach.Rows[dem].Cells[0].Value = dem + 1;
        }
        string dongia;
        string masach;
        string TenSachHD;
        string TheLoai;
        private void grvDanhMucSach_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            int dem = e.RowIndex;
            masach = grvDanhMucSach.Rows[dem].Cells["MaSach"].Value.ToString();
            TenSachHD= grvDanhMucSach.Rows[dem].Cells["TenSach1"].Value.ToString();
            dongia = grvDanhMucSach.Rows[dem].Cells["DonGia"].Value.ToString();
            TheLoai = grvDanhMucSach.Rows[dem].Cells["TenTheLoai"].Value.ToString();
        }
        string tongtien;
        private void tinhtongtien()
        {
            double soLuong = 0;
            double donGia = 0;
            double thanhTien = 0;
            try
            {
                double.TryParse(txtSoLuong.Text, out soLuong);
                double.TryParse(dongia, out donGia);
                thanhTien = soLuong * donGia;
                tongtien = thanhTien.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Lỗi:" + ex.Message);

            }

        }
        private void GrvDanhSachKH_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            if(GrvDanhSachKH.Rows.Count>0)
            {
                int dem = e.RowIndex;
                txtTenKH.Text = GrvDanhSachKH.Rows[dem].Cells["HoTen"].Value.ToString();
                txtGhiChu.Text = GrvDanhSachKH.Rows[dem].Cells["GhiChu"].Value.ToString();
                txtDiaChi.Text = GrvDanhSachKH.Rows[dem].Cells["DiaChi"].Value.ToString();
                txtDT.Text = GrvDanhSachKH.Rows[dem].Cells["DienThoai"].Value.ToString();
                txtSoLuong.Text = GrvDanhSachKH.Rows[dem].Cells["SoLuong"].Value.ToString();
                txtTongTien.Text = GrvDanhSachKH.Rows[dem].Cells["TongTien1"].Value.ToString();
            }          
        }
        private int rowIndex = 0;
        private int CheckExitName(string strName)
        {
            int index = 0;
            foreach (DataGridViewRow row in GrvDanhSachKH.Rows)
            {
                string matHang = row.Cells["MaSach1"].Value.ToString();
                if (strName == matHang)
                {
                    MessageBox.Show("Mặt hàng đã tồn tại!");
                    return index;
                }
                index++;
            }
            return -1;
        }
        private bool CheckEditName(string strName)
        {
            for (int i = 0; i < GrvDanhSachKH.Rows.Count; i++)
            {
                if (i == rowIndex)
                    continue;
                string matHang = GrvDanhSachKH["MaSach1", i].Value.ToString();
                if (strName == matHang)
                {
                    MessageBox.Show("Mặt hàng đã tồn tại!");
                    return true;
                }
            }
            return false;
        }

        private void btnXoa_Click_1(object sender, EventArgs e)
        {
            if (DialogResult.Yes == MessageBox.Show("Bạn có chắc muốn xoá hay không?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
            {
                GrvDanhSachKH.Rows.RemoveAt(rowIndex);
                MessageBox.Show("Đã xóa thành công");
            }
            tinhtongtien();
        }
        bool ketqua = false;
        int mahoadon;
        private void btnTaoMoi_Click(object sender, EventArgs e)
        {
            KhachHang_OBJ obj = new KhachHang_OBJ();
            TinhTongTienall();
            obj.MaKhachHang = 0;
            obj.HoTen = txtTenKH.Text;
            obj.GioiTinh = optNam.Checked ? "1" : "0";
            obj.DiaChi = txtDiaChi.Text;
            obj.GhiChu = txtGhiChu.Text;
            obj.DienThoai = txtDT.Text;
            obj.Option = Convert.ToString(1);
            ketqua = BUS.KhachHang_BUS.Customer_Insert_Up(obj);
            if (!ketqua)
            {
                MessageBox.Show("Thêm sửa khách hàng thất bại !");
            }
            else
            {
                MessageBox.Show("Thêm sửa khách hàng thành công!");
                HoaDon_OBJ hdobj = new HoaDon_OBJ();
                hdobj.TongTien = double.Parse(Tongtienall);
                hdobj.TenDangNhap = TenDN;
                hdobj.MaKhachHang = Convert.ToInt32(_KhachHangBUS.MaKhachHang().Rows[0]["MaKhachHang"].ToString());
                hdobj.KieuHoaDon = "Hoá đơn xuất";
                BUS.HoaDon_BUS.Customer_Insert(hdobj);
                ChiTietHoaDon_OBJ objh = new ChiTietHoaDon_OBJ();
                DataTable dt = new DataTable();
                dt = _HoaDonBUS.MaHoaDon();
                mahoadon = Convert.ToInt32(dt.Rows[0]["MaHoaDon"].ToString());
                foreach (DataGridViewRow row in GrvDanhSachKH.Rows)
                {
                    objh.MaHoaDon = mahoadon;
                    objh.MaSach=Convert.ToInt32(row.Cells["MaSach1"].Value.ToString());
                    objh.DonGia = Convert.ToInt32(row.Cells["DonGia1"].Value.ToString());
                    objh.SoLuong = Convert.ToInt32(row.Cells["SoLuong"].Value.ToString());
                    objh.ThanhTien = Convert.ToInt32(row.Cells["TongTien1"].Value.ToString());
                    ketqua = BUS.ChiTietHoaDon_BUS.Customer_Insert(objh);
                }
            }
        }
        private void btnSua_Click_1(object sender, EventArgs e)
        {
            string matHang = txtMaSach.Text;
            if (CheckEditName(matHang) == true)
                return;
            DataGridViewRow row = GrvDanhSachKH.Rows[rowIndex];
            float soLuong = 0;
            float.TryParse(txtSoLuong.Text, out soLuong);
            row.Cells[0].Value = GrvDanhSachKH.Rows.Count + 1;
            row.Cells[1].Value = txtMaSach.Text;
            row.Cells[2].Value = txtTenKH.Text;
            row.Cells[3].Value = txtGhiChu.Text;
            row.Cells[4].Value = optNam.Checked ? "Nam" : "Nữ";
            row.Cells[5].Value = txtDiaChi.Text;
            row.Cells[6].Value = txtDT.Text;
            row.Cells[7].Value = txtTenSach.Text;
            row.Cells[8].Value = soLuong;
            row.Cells[9].Value = dongia;
            row.Cells[10].Value = tongtien;
            tinhtongtien();
        }
        private void btnTK_Click(object sender, EventArgs e)
        {
            if(txtMaSach.Text=="" && txtTheLoai.Text=="")
            {
                grvDanhMucSach.DataSource = _SachBUS.Search_Sach("1", txtTenSach.Text, "",0);
            }
            else if(txtMaSach.Text==""&&txtTenSach.Text=="")
            {
                grvDanhMucSach.DataSource = _SachBUS.Search_Sach("2","",txtTheLoai.Text, 0);
            }
            else if(txtTheLoai.Text==""&&txtTenSach.Text=="")
            {
                grvDanhMucSach.DataSource = _SachBUS.Search_Sach("3", "","",Convert.ToInt32(txtMaSach.Text));
            }
        }

        private void txtSoLuong_TextChanged(object sender, EventArgs e)
        {
            tinhtongtien();
            if (txtSoLuong.Text != "" && int.TryParse(txtSoLuong.Text, out a) == false)
            {
                MessageBox.Show("Bạn đã copy pase thất bại :p");
                txtSoLuong.Clear();//"" nó lại hiện thông báo :D
            }
        }
        int a = 0;
        private void txtSoLuong_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (char.IsDigit(e.KeyChar) == false && char.IsControl(e.KeyChar) == false && e.KeyChar != '.')//Ký tự ĐK là is.Control có thể xoá khi nhập lỗi,nhập được dấu '.'
                e.Handled = true;
        }

        private void txtTenSach_TextChanged(object sender, EventArgs e)
        {
            txtMaSach.Clear();
            txtTheLoai.Clear();
        }

        private void txtMaSach_TextChanged(object sender, EventArgs e)
        {
            txtTheLoai.Clear();
            txtTenSach.Clear();
        }

        private void txtTheLoai_TextChanged(object sender, EventArgs e)
        {
            txtTenSach.Clear();
            txtMaSach.Clear();          
        }
        private void button2_Click(object sender, EventArgs e)
        {
            GrvDanhSachKH.Rows.Clear();
            txtTenKH.Enabled = true;
            txtDiaChi.Enabled = true;
            txtDT.Enabled = true;
            txtGhiChu.Enabled = true;
        }
    }
}
